<?php
require_once 'Junction/Db/Adapter.php';
require_once 'Junction/Db/Exception.php';
require_once 'Junction/Db/Service.php';
require_once 'Junction/Libs/creole/Creole.php';

class Junction_Db_Creole_Service implements Junction_Db_Service {

	/**
	 * Creole database handle.
	 *
	 * @var Connection
	 */
	private $_dbh;
	private $_affectedRows;

	public function __construct() {
		$this->_affectedRows = 0;
	}

	/**
	 * @throws Junction_Db_Exception
	 * @param Junction_Db_Adapter $adapter
	 */
	public function connect(Junction_Db_Adapter $adapter) {
		$this->_dbh = $adapter->getConnection();
	}

	/**
	 * @throws Junction_Db_Exception
	 */
	private function checkConnection() {
		if (!isset($this->_dbh)) {
			throw new Junction_Db_Exception('Junction is not connected to the database.');
		}
	}

	/**
	 * @throws Junction_Db_Exception
	 * @param String $query
	 * @param array $params
	 * @return boolean
	 */
	public function save($query, array $params = null) {
		$this->checkConnection();
		try {
			$stmt = $this->_dbh->prepareStatement($query);
			$this->_affectedRows = $stmt->executeUpdate($params);
			return ($this->_affectedRows > 0);
		} catch (SQLException $e) {
			throw new Junction_Db_Exception($e->getMessage());
		}
	}

	/**
	 * @throws Junction_Db_Exception
	 * @param String $query
	 * @param array $params
	 * @return array
	 */
	public function select($query, array $params = null) {
		$this->checkConnection();
		try {
			$stmt = $this->_dbh->prepareStatement($query);
			// TODO read the result set into an array...
			return $stmt->executeQuery($params);
		} catch (SQLException $e) {
			throw new Junction_Db_Exception($e->getMessage());
		}
	}

	/**
	 * @throws Junction_Db_Exception if no database connection exists.
	 * @return int
	 */
	public function lastInsertId() {
		$this->checkConnection();
		return $this->_dbh->getIdGenerator()->getId();
	}

	/**
	 * @throws Junction_Db_Exception if no database connection exists.
	 * @return int
	 */
	public function affectedRows() {
		$this->checkConnection();
		return $this->_affectedRows;
	}
}
?>